package event;

import org.hibernate.Session;

import java.util.Date;

import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.WKTReader;
import com.vividsolutions.jts.io.ParseException;

import util.HibernateUtil;

public class EventManager {

	public static void main(String[] args) {
		EventManager mgr = new EventManager();

		if (args[0].equals("store")) {
			mgr.createAndStoreEvent("My Event", new Date(), args[1]);
		}

		HibernateUtil.getSessionFactory().close();
	}

	private void createAndStoreEvent(String title, Date theDate, String wktPoint) {

		// First interpret the WKT string to a point
		WKTReader fromText = new WKTReader();
		Geometry geom = null;
		try {
			geom = fromText.read(wktPoint);
		} catch (ParseException e) {
			throw new RuntimeException("Not a WKT string:" + wktPoint);
		}
		if (!geom.getGeometryType().equals("Point")) {
			throw new RuntimeException("Geometry must be a point. Got a "
					+ geom.getGeometryType());
		}

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();

		session.beginTransaction();

		Event theEvent = new Event();
		theEvent.setTitle(title);
		theEvent.setDate(theDate);
		theEvent.setLocation((Point) geom);
		session.save(theEvent);

		session.getTransaction().commit();
	}
}
